#include "clientconnection.h"

ClientConnection::ClientConnection(QObject *parent) :
    QObject(parent)
{
    m_tcpSocket = new QTcpSocket(this);
    buffer = "";
    //connections for QTcpSocket work
    connect(m_tcpSocket, SIGNAL(readyRead()),
            this, SLOT(slotRecieve()));
    connect(m_tcpSocket, SIGNAL(connected()),
            this, SLOT(slotConnectionSuccessfull()));
    connect(m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(slotConnectionError(QAbstractSocket::SocketError)));
    connect(m_tcpSocket, SIGNAL(disconnected()),
            this, SLOT(slotDisconnectedFromSocket()));

}

ClientConnection::~ClientConnection()
{
    qDebug() << "ClientConnection::~ClientConnection()";
    if (connected())
    {
        disconnectFromSocket();
    }
    delete m_tcpSocket;
}

void ClientConnection::sendMessage(QString message)
{
    QByteArray  arrBlock;
    QDataStream out(&arrBlock,QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_8);

    //first bytes are size of message

    out << quint16(0);

    out << message.toUtf8();
    out.device()->seek(0);
    out << quint16(arrBlock.size() - sizeof(quint16));
    m_tcpSocket->write(arrBlock);
    qDebug() << "ClientConnection sendMessage(str="
             << message
             << ")";
}

void ClientConnection::connectToSocket(QString _ip, int _port)
{
    if (!connected())
    {
        m_tcpSocket->connectToHost(_ip, _port);
        qDebug() << "ClientConnection trying to connect to Socket";
//        if (!m_tcpSocket->waitForConnected(TIMEOUT))
//        {
//            emit connectionError(QAbstractSocket::error());
//            return;
//        }
    }
}

void ClientConnection::disconnectFromSocket()
{
    if (!connected())
    {
        return;
    }

    qDebug() << "ClientConnection disconnectedFromSocket";
    m_tcpSocket->disconnectFromHost();
}

bool ClientConnection::connected()
{
    if (m_tcpSocket->state() != QAbstractSocket::ConnectedState &&
            m_tcpSocket->state() != QAbstractSocket::ConnectingState)
    {
        return false;
    }
    return true;
}

void ClientConnection::slotConnectionSuccessfull()
{
    qDebug() << "ClientConnection signalConnectionSuccessfull";
    emit signalConnectionSuccessfull();
}

void ClientConnection::slotConnectionError(QAbstractSocket::SocketError err)
{
    qDebug() << "ClientConnection signalConnectionError";
    emit signalConnectionError(err);
}

void ClientConnection::slotDisconnectedFromSocket()
{
    qDebug() << "ClientConnection signalDisconnectedFromSocket";
    emit signalDisconnectedFromSocket();
}

void ClientConnection::slotRecieve()
{
    qDebug() << "ClientConnection::slotRecieve()";
    QDataStream in(m_tcpSocket);
    in.setVersion(QDataStream::Qt_4_8);
    quint16 m_nNextBlockSize = 0;
    for (;;) {
        if (!m_nNextBlockSize)
        {
            if (m_tcpSocket->bytesAvailable() < sizeof(quint16))
            {
                break;
            }
            qDebug() << "ClientConnection::slotRecieve() is reading";
            in >> m_nNextBlockSize;
        }

        if (m_tcpSocket->bytesAvailable() < m_nNextBlockSize)
        {
            break;
        }

        QByteArray data;
        in >> data;

        //all bytes pushed in buffer
        //finding position of "\r\n"
        //copying complite message and signalReceived()
        //removing complite message from buffer
        buffer.append(data);
        int pos = buffer.indexOf(delimetrs::eom);
        while (pos != -1)
        {
            QString str = buffer.left(pos + 2);
            buffer.remove(0,pos + 2);
            qDebug() << "ClientConnection slotRecieve (" << str << ")";
            emit signalReceived(str);
            pos = buffer.indexOf(delimetrs::eom);
        }

        m_nNextBlockSize = 0;
    }

}
